package com.biz.primus.ms.sms.dao.sepecification;

import com.biz.primus.model.misc.vo.SendTaskQuery;
import com.biz.primus.ms.sms.dao.po.SendTask;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * SendTaskSpecfication
 *
 * @author JKLiues
 * @date 2017年10月26日
 */
public class SendTaskSpecification implements Specification<SendTask> {

    private SendTaskQuery reqVo;

    public SendTaskSpecification(SendTaskQuery reqVo) {
        this.reqVo = reqVo;
    }

    @Override
    public Predicate toPredicate(Root<SendTask> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

        List<Predicate> predicates = Lists.newArrayList();
        String mobileEq = reqVo.getMobileEq();
        if (StringUtils.isNotBlank(mobileEq)) {
            predicates.add(cb.equal(root.get("receiver").as(String.class), mobileEq));
        }
        String signatureEq = reqVo.getSignatureEq();
        if (StringUtils.isNotBlank(signatureEq)) {
            predicates.add(cb.equal(root.get("signature").as(String.class), signatureEq));
        }

        Date createTimestampBegin = reqVo.getCreateTimestampBegin();
        if (createTimestampBegin != null) {
            predicates.add(cb.greaterThan(root.get("createTimestamp").as(Timestamp.class), createTimestampBegin));
        }

        Date createTimestampEnd = reqVo.getCreateTimestampEnd();
        if (createTimestampEnd != null) {
            predicates.add(cb.lessThan(root.get("createTimestamp").as(Timestamp.class), createTimestampEnd));
        }

        String channelNameEq = reqVo.getChannelNameEq();
        if (StringUtils.isNotBlank(channelNameEq)) {
            predicates.add(cb.equal(root.get("channelName").as(String.class), channelNameEq));
        }

        String providerNameEq = reqVo.getProviderNameEq();
        if (StringUtils.isNotBlank(providerNameEq)) {
            predicates.add(cb.equal(root.get("providerName").as(String.class), providerNameEq));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
}